package com.zhongkun.datahome.service.export.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
public class MergeCellHandler implements CellWriteHandler {
    private String lastAppointmentName;
    private String lastOwner;

    // 预约名称列（索引0）的行列变量
    private int lastStartRow0 = -1;
    private int lastEndRow0 = -1;

    // 指定业主列（索引1）的行列变量
    private int lastStartRow1 = -1;
    private int lastEndRow1 = -1;

    private int headerRowCount = 1;
    private Set<String> mergedRegions = new HashSet<>();
    private List<List<String>> dataList;

    public MergeCellHandler(List<List<String>> dataList) {
        this.dataList = dataList;
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) return;

        Row currentRow = cell.getRow();
        int currentRowNum = currentRow.getRowNum();
        int dataRowIndex = currentRowNum - headerRowCount;
        if (dataRowIndex < 0 || dataRowIndex >= dataList.size()) {
            log.warn("当前行号{}无对应数据，跳过合并逻辑", currentRowNum);
            return;
        }
        List<String> data = dataList.get(dataRowIndex);

        // 1. 处理"预约名称"列（索引0）
        if (data.get(0) != null) {
            if (!data.get(0).equals(lastAppointmentName)) {
                // 新值：合并上一个连续区域（如果有）
                if (lastStartRow0 != -1 && lastEndRow0 != -1) {
                    mergeRegion(writeSheetHolder.getSheet(), lastStartRow0, lastEndRow0, 0);
                }
                // 重置连续区域为当前行
                lastAppointmentName = data.get(0);
                lastStartRow0 = currentRowNum;
                lastEndRow0 = currentRowNum;
            } else {
                // 相同值：扩展当前连续区域的结束行
                lastEndRow0 = currentRowNum;
            }
        }

        // 2. 处理"指定业主"列（索引1）
        if (data.get(1) != null) {
            if (!data.get(1).equals(lastOwner)) {
                // 新值：合并上一个连续区域（如果有）
                if (lastStartRow1 != -1 && lastEndRow1 != -1) {
                    mergeRegion(writeSheetHolder.getSheet(), lastStartRow1, lastEndRow1, 1);
                }
                // 重置连续区域为当前行
                lastOwner = data.get(1);
                lastStartRow1 = currentRowNum;
                lastEndRow1 = currentRowNum;
            } else {
                // 相同值：扩展当前连续区域的结束行
                lastEndRow1 = currentRowNum;
            }
        }
    }

    private void mergeRegion(org.apache.poi.ss.usermodel.Sheet sheet, int firstRow, int lastRow, int col) {
        // 合并逻辑保持不变，仅修改行列变量为列独立的变量
        String regionKey = generateRegionKey(firstRow, lastRow, col, col);
        if (mergedRegions.contains(regionKey)) {
            return;
        }
        try {
            if (!isMergedRegionExist(sheet, firstRow, lastRow, col)) {
                sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, col, col));
                mergedRegions.add(regionKey);
            }
        } catch (IllegalArgumentException e) {
            log.error("合并区域失败：行{}-{}，列{}，原因：{}", firstRow, lastRow, col, e.getMessage());
        }
    }

    /**
     * 生成区域唯一标识（格式："firstRow,lastRow,firstCol,lastCol"）
     */
    private String generateRegionKey(int firstRow, int lastRow, int firstCol, int lastCol) {
        return String.format("%d,%d,%d,%d", firstRow, lastRow, firstCol, lastCol);
    }

    /**
     * 检查合并区域是否已存在（通过 POI 的合并区域列表）
     */
    private boolean isMergedRegionExist(org.apache.poi.ss.usermodel.Sheet sheet, int firstRow, int lastRow, int col) {
        for (CellRangeAddress mergedRegion : sheet.getMergedRegions()) {
            if (mergedRegion.getFirstRow() == firstRow
                    && mergedRegion.getLastRow() == lastRow
                    && mergedRegion.getFirstColumn() == col
                    && mergedRegion.getLastColumn() == col) {
                return true;
            }
        }
        return false;
    }

    /**
     * 数据写入完成后，合并最后一行的连续区域（两列独立处理）
     */
    public void finishMerge(WriteSheetHolder writeSheetHolder) {
        // 处理预约名称列的最后一个区域
        if (lastStartRow0 != -1 && lastEndRow0 != -1 && dataList != null && !dataList.isEmpty()) {
            int lastExcelRow = headerRowCount + (dataList.size() - 1);
            if (lastEndRow0 < lastExcelRow) {
                lastEndRow0 = lastExcelRow;
            }
            mergeRegion(writeSheetHolder.getSheet(), lastStartRow0, lastEndRow0, 0);
        }

        // 处理指定业主列的最后一个区域
        if (lastStartRow1 != -1 && lastEndRow1 != -1 && dataList != null && !dataList.isEmpty()) {
            int lastExcelRow = headerRowCount + (dataList.size() - 1);
            if (lastEndRow1 < lastExcelRow) {
                lastEndRow1 = lastExcelRow;
            }
            mergeRegion(writeSheetHolder.getSheet(), lastStartRow1, lastEndRow1, 1);
        }
    }
}